package com.gilgamesh.mall.reptile.service;

import com.gilgamesh.mall.reptile.bean.JDPrice;
import com.gilgamesh.mall.reptile.bean.P;
import com.gilgamesh.mall.reptile.bean.R;
import com.gilgamesh.mall.reptile.util.JDPriceGetter;
import lombok.RequiredArgsConstructor;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

/**
 * @author yanm
 * @date 2021/1/19 10:33
 **/
@Service
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
public class ReptileService {

    private final JDPriceGetter jdPriceGetter;

    public String urlEncode(String keyWord) {
        try {
            return URLEncoder.encode(keyWord, "UTF-8");
        } catch (UnsupportedEncodingException e) {
            return null;
        }
    }

    public String getUrl(String keyWord,Integer page) {
        keyWord = urlEncode(keyWord);
        return "https://search.jd.com/Search?keyword=" + keyWord + "&page="+page+"&enc=utf-8&pvid=960884579647452e8e1cfe76341467ff";
    }


    public List<R> getResponse(String keyWord,Integer page) {
        String url = getUrl(keyWord,page);
        List<R> rs = new ArrayList<>();
        searchScollPage(rs, url);
        return rs;
    }

    private List<R> searchScollPage(List<R> rs, String url) {
        try {
            Document doc = Jsoup.connect(url).get();
            Elements els = doc.getElementsByClass("gl-i-wrap");
            for (Element el : els) {
                R r = new R();
                Elements tagAs = el.getElementsByTag("a");
                r.setShowTitle(getText(el, "p-name"));
                r.setCurrentPrice(getText(el, "p-price"));
                if (tagAs.size() > 0) {
                    String detailHref = tagAs.get(0).attr("href");
                    r.setDetailUrl("https:" + detailHref);
                    Elements showImgs = tagAs.get(0).getElementsByTag("img");
                    if (showImgs.size() > 0) {
                        String src = showImgs.get(0).attr("data-lazy-img");
                        String width = showImgs.get(0).attr("width");
                        String height = showImgs.get(0).attr("height");
                        r.setShowHeight(height);
                        r.setShowWidth(width);
                        r.setShowPicList("https:" + src);
                    }
                }

                searchDetailPage(r, r.getDetailUrl());
                rs.add(r);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return rs;
    }

    private R searchDetailPage(R r, String url) throws Exception {
        Document doc = Jsoup.connect(url).get();
        r.setTitle(getText(
                doc, "sku-name"
        ));
        Element img = doc.getElementById("spec-img");
        if(r.getDetailImgeUrl() == null){
            r.setDetailImgeUrl(new ArrayList<>());
        }
        if(StringUtils.hasText(img.attr("data-origin"))) {
            r.getDetailImgeUrl().add("http:" + img.attr("data-origin"));
        }
        r.setDetailImageWidth(img.attr("width"));
        r.setDetailImageHeight(img.attr("height"));
        if(!StringUtils.hasText(r.getDetailImageHeight())){
            r.setDetailImageHeight(r.getDetailImageWidth());
        }
        Element choose = doc.getElementById("choose-attr-1");
        Elements dds = choose.getElementsByClass("dd");
        for (Element dd : dds) {
            Elements items = dd.getElementsByClass("item");
            for (Element item : items) {
                P p = new P();
                p.setSku_id(item.attr("data-sku"));
                p.setTypeName(item.attr("data-value"));
                Elements imgs = item.getElementsByTag("img");
                if (imgs.size() > 0) {
                    p.setScrollImageUrl("http:" + imgs.get(0).attr("src"));
                    p.setChooseImageHeight(imgs.get(0).attr("height"));
                    p.setChooseImageWidth(imgs.get(0).attr("width"));
                    p.setChooseImageAlt(imgs.get(0).attr("alt"));
                }
                if (r.getPs() == null) {
                    r.setPs(new ArrayList<>());
                }
                JDPrice jDprice = jdPriceGetter.getJDprice(p.getSku_id());
                p.setJdPrice(jDprice);
                r.getPs().add(p);
            }
        }
        return r;
    }

    private String getText(Element element, String className) {
        Elements elNames = element.getElementsByClass(className);
        if (elNames.size() > 0) {
            for (Element elName : elNames) {
                if (StringUtils.hasText(elName.text())) {
                    return elName.text();
                }
            }
        }
        return null;
    }

    public JDPrice getPrice(String skuId){
        return jdPriceGetter.getJDprice(skuId);
    }


}
